package com.example.demo.jucConcurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * juc类库中提供了Condition类来实现线程之间的协调,可以在Condition上调用await()方法使用等待线程,其他调用
 * signal()或者signalAll()方法获取线程相比wait()这种等待方式,可以指定等待的条件,因此更加灵活
 *
 * 使用Lock来获取一个Condition对象
 */
public class AwaitSignalExample {

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();


    public  void  before(){
        lock.lock();
        try {
            System.out.println("before");
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public  void after(){
        lock.lock();
        try {
            condition.await();
            System.out.println("after");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        AwaitSignalExample example = new AwaitSignalExample();
        executorService.execute(()->example.after());
        executorService.execute(()->example.before());
    }
}
